import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
import pcap from 'pcap';

@Injectable()
export class SnifferService implements OnModuleInit {
  private readonly logger = new Logger(SnifferService.name);
  onModuleInit() {
    this.startCapture();
  }

  private startCapture() {
    // 1. 创建抓包会话
    const session = pcap.createSession('eth0', {
      filter: 'tcp port 80 or tcp port 443', // 过滤HTTP/HTTPS流量
      buffer_size: 10 * 1024 * 1024, // 10MB缓冲区
      // filter: 'tcp port 3000', // 监听3000端口
      // promiscuous: true,
    });
    // 2. 数据包解析器
    session.on('packet', (rawPacket) => {
      const packet = pcap.decode.packet(rawPacket);
      this.logger.debug('捕获数据包:', packet);
    });
    // 3. 错误处理
    session.on('error', (error) => {
      this.logger.error(`抓包失败: ${error}`);
    });
    this.logger.log('-----开始监听网络流量-----');
  }
}
